package cn.pet.service.manage.controller;


import cn.pet.service.manage.common.Response;
import cn.pet.service.manage.entity.PetCart;
import cn.pet.service.manage.entity.PetOrder;
import cn.pet.service.manage.entity.PetOrderDetail;
import cn.pet.service.manage.entity.PetUser;
import cn.pet.service.manage.entity.api.Result;
import cn.pet.service.manage.entity.dto.OrderDTO;
import cn.pet.service.manage.entity.dto.OrderSearch;
import cn.pet.service.manage.entity.vo.OrderVO;
import cn.pet.service.manage.mapstruct.OrderMapstruct;
import cn.pet.service.manage.service.PetAddressService;
import cn.pet.service.manage.service.PetCartService;
import cn.pet.service.manage.service.PetOrderDetailService;
import cn.pet.service.manage.service.PetOrderService;
import cn.pet.service.manage.utils.OrderIDGenerate;
import cn.pet.service.manage.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 
 * @since 2023-02-11
 */
@RestController
@RequestMapping("/manage/petOrder")
public class PetOrderController {

    @Resource
    private PetOrderService petOrderService;

    @Resource
    private PetOrderDetailService petOrderDetailService;

    @Resource
    private PetCartService petCartService;


    @GetMapping("list")
    public Object list(OrderSearch search){
        Integer userId = SecurityUtil.getUserId();
        if (null == userId){
            return Result.error("请先登录");
        }
        search.setUserId(userId);
        return Response.success(new PageInfo<>(petOrderService.listByPage(search)));
    }

    @GetMapping("listByUserId")
    public Object listByUserId(OrderSearch search){
//        Integer userId = SecurityUtil.getUserId();
//        if (null == userId){
//            return Result.error("请先登录");
//        }
        return Result.ok("success",petOrderService.listByPage(search));
    }

    @GetMapping("adminList")
    public Object adminList(OrderSearch search){
        return Response.success(new PageInfo<>(petOrderService.listByPage(search)));
    }

    /**
     * 订单详情
     * @param id 订单号
     * @return
     */
    @GetMapping("detail/{id}")
    public Object detail(@PathVariable("id") String id){
        //查询订单信息
        OrderVO orderVO = petOrderService.detailById(id);
        //查询该订单的商品列表信息
        orderVO.setOrderDetailVOS(petOrderDetailService.listByOrderId(id));
        return Result.ok("success",orderVO);
    }

    /**
     * 订单状态更新--订单结算
     * @param orderDTO
     * @return
     */
    @PutMapping("statusUpdate")
    public Object statusUpdate(@RequestBody OrderDTO orderDTO){
        PetOrder petOrder = new PetOrder();
        petOrder.setId(orderDTO.getId());
        petOrder.setStatus(orderDTO.getStatus());
        if (!petOrderService.updateById(petOrder)){
            return Result.error("状态更新失败");
        }
        return Result.ok("状态更新成功");
    }


    /**
     * 订单生成
     * @param orderDTO
     * @return
     */
    @PostMapping("generateOrder")
    @Transactional
    public Object generateOrder(@RequestBody OrderDTO orderDTO){
        Integer userId = SecurityUtil.getUserId();
        if (userId==null){
            return Result.error("请先登录");
        }
        orderDTO.setUserId(userId);
        //写入订单信息
        PetOrder petOrder = new PetOrder();
        BeanUtils.copyProperties(orderDTO,petOrder);
//        petOrder = OrderMapstruct.INSTANCE.orderDTOtoOrder(orderDTO,petOrder);
        petOrder.setId(OrderIDGenerate.getOrderNumber());
        if (!petOrderService.save(petOrder)){
            return Result.error("下单失败");
        }
        List<Integer> cartIds = new ArrayList<>();
        orderDTO.getOrderDetails().forEach(x->{
            x.setOrderId(petOrder.getId());
            cartIds.add(x.getCarId());
        });
        //批量写入订单详情
        if (!petOrderDetailService.saveBatch(orderDTO.getOrderDetails())){
            return Result.error("下单失败");
        }
        //删除购物车商品
        petCartService.removeBatchByIds(cartIds);
        return Result.ok("下单成功");
    }

    /**
     * 删除订单
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    @Transactional
    public Object delete(@PathVariable("id") String id){
        //根据订单ID查询订单心情列表
        LambdaQueryWrapper<PetOrderDetail> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(PetOrderDetail::getOrderId,id);
        List<PetOrderDetail> list = petOrderDetailService.list(queryWrapper);
        List<Integer> detailIds = list.stream().map(PetOrderDetail::getId).collect(Collectors.toList());
        //删除详情信息
        if (!petOrderDetailService.removeBatchByIds(detailIds)){
            return Result.error("删除失败");
        }
        if (!petOrderService.removeById(id)){
            return Result.error("删除失败");
        }
        return Result.ok("删除成功");
    }

}
